package com.alex.blog.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class HelloController {

    @GetMapping({"/", "/home"})
    public String index(Model model) {
        model.addAttribute("msg", "hello shiro");
        return "index";
    }

    @RequestMapping("login")
    public String login() {
        return "login";
    }

    @RequestMapping("doLogin")
    public String doLogin(String username, String password, Model model) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);
            return "redirect:/";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名错误");
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误");
        } catch (UnknownError e) {
            model.addAttribute("未知错误");
        }
        return "login";
    }

    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/";
    }

    @GetMapping("info")
    public String info() {
        return "info";
    }

    @RequestMapping("user/add")
    public String add() {
        return "user/add";
    }

    @RequestMapping("user/del")
    public String del() {
        return "user/del";
    }

    @RequestMapping("user/get")
    public String get() {
        return "user/query";
    }

    @RequestMapping("no-access")
    public String test01() {
        return "no-access";
    }

    @ResponseBody
    @RequestMapping("static")
    public String test02() {
        return "static";
    }

    @ResponseBody
    @RequestMapping("secret")
    public String test03() {
        return "secret";
    }
}
